import java.text.MessageFormat;
import java.util.Objects;

/**
 * 项目中用于集中管理redis key命名
 * 通过of(参数..)方法自动生成具体的key
 *
 * @author sk.z
 */
public enum RedisKey {

    REQUEST_NUMBER("rt:nr"),    //请求数量
    CONCURRENT_INSERT_LOCK("ct:it:lk:{0}:{1}"),   //货币写入锁[0:userId][1:type]
    UNREAD_MESSAGE_NUMBER("ud:me:nr:{0}");  //未读消息数量[0:userId]

    private static final String PROJECT_NAME = "pn";

    private final int paramNum;
    private final String key;

    RedisKey(String key) {
        this.key = PROJECT_NAME + ":" + key;

        int count = 0;
        for (char c : key.toCharArray()) {
            if (c == '{') {
                count++;
            }
        }
        this.paramNum = count;
    }

    /**
     * 获取组装key
     *
     * @param paramArr 参数数组
     */
    public String of(String... paramArr) {
        if (Objects.isNull(paramArr)){
            return this.key;
        }
        if (paramArr.length != this.paramNum) {
            throw new IllegalArgumentException("redis key 组装参数个数不符");
        }
        return MessageFormat.format(this.key, paramArr);
    }

    public static void main(String[] args) {
        System.out.println(REQUEST_NUMBER.of());
        System.out.println(CONCURRENT_INSERT_LOCK.of("100001","1"));
    }

}
